package com.example.controller;

import cn.hutool.system.UserInfo;
import cn.idev.excel.FastExcel;
import cn.idev.excel.write.handler.context.CellWriteHandlerContext;
import cn.idev.excel.write.metadata.style.WriteCellStyle;
import cn.idev.excel.write.style.HorizontalCellStyleStrategy;
import cn.idev.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import com.example.config.ExcelMergeHandler;
import com.example.constant.Constant;
import com.example.entity.UserVO;
import com.example.listener.DataListener;
import com.example.resp.ResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/file")
@Api(value = "文件操作接口", description = "文件类的上传下载等相关操作")
public class FileController {

    @PostMapping("/upload")
    @ApiOperation(value = "Excel上传", notes = "Excel上传")
    public ResultVo upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResultVo.failure("上传文件无效！");
        }
        try {
            DataListener<UserInfo> userInfoExcelListener = new DataListener<>();
            FastExcel.read(file.getInputStream(), UserInfo.class, userInfoExcelListener).sheet().doRead();
            // 得到读取数据
            List<UserInfo> dataList = userInfoExcelListener.getRows();
            log.info("总共读取到{}条数据", dataList.size());
            return ResultVo.success(Constant.SUCCESS);
        } catch (IOException e) {
            log.error("文件处理失败", e);
            return ResultVo.failure(Constant.FAILURE);
        }
    }

    @GetMapping("/download")
    public void download(HttpServletResponse response) throws Exception {
        List<UserVO> list = Constant.USER_INFO_LIST;
        String fileName = URLEncoder.encode("人员信息", "UTF-8");
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.addHeader("Pargam", "no-cache");
        response.addHeader("cache-Control", "no-cache");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        // 需要合并的列
        int[] mergeColumnIndex = {3, 4};
        // 因为表头有两行 所以从第二行后开始合并
        int mergeRowIndex = 2;
        // 头的策略
        WriteCellStyle headStyle = new WriteCellStyle();
        headStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        headStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        // 内容的策略
        WriteCellStyle contentStyle = new WriteCellStyle();
        // 设置垂直居中
        contentStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 设置水平居中
        contentStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        // 设置边框
        contentStyle.setBorderTop(BorderStyle.THIN);
        contentStyle.setTopBorderColor(IndexedColors.BLACK.index);
        contentStyle.setBorderRight(BorderStyle.THIN);
        contentStyle.setRightBorderColor(IndexedColors.BLACK.index);
        contentStyle.setBorderBottom(BorderStyle.THIN);
        contentStyle.setBottomBorderColor(IndexedColors.BLACK.index);
        contentStyle.setBorderLeft(BorderStyle.THIN);
        contentStyle.setLeftBorderColor(IndexedColors.BLACK.index);
        // 这个策略是 头是头得样式 内容是内容的样式
        HorizontalCellStyleStrategy cellStyleStrategy = new HorizontalCellStyleStrategy(headStyle, contentStyle);
        // 写入数据
        try (ServletOutputStream output = response.getOutputStream()) {
            FastExcel.write(output, UserInfo.class)
                    .sheet("员工信息")
                    .registerWriteHandler(new ExcelMergeHandler(mergeRowIndex, mergeColumnIndex))
                    .registerWriteHandler(cellStyleStrategy)
                    .registerWriteHandler(new AbstractColumnWidthStyleStrategy() {
                        @Override
                        protected void setColumnWidth(CellWriteHandlerContext context) {
                            Sheet sheet = context.getWriteSheetHolder().getSheet();
                            int columnIndex = context.getCell().getColumnIndex();
                            if (columnIndex == 0) {
                                // 列宽50
                                sheet.setColumnWidth(columnIndex, 5000);
                            } else {
                                // 列宽40
                                sheet.setColumnWidth(columnIndex, 4000);
                            }
                        }
                    }).doWrite(list);
        }catch (Exception e){
            log.error("文件下载失败", e);
        }
    }

}